import Taro, { useEffect, useState } from "@tarojs/taro";
import { View, Image, ScrollView } from "@tarojs/components";
// import { AtTabs, AtTabsPane } from "taro-ui";
import "./index.scss";
import { CONCAT_CDN_IMAGE_ORIGIN } from "@/utils/test";
import { ShowMessageBox } from "./box";
import { CustomRequest } from "@/utils/request";
import { apiVotePost, apiVotes, IItem, programTypeConfig } from "./config";
import { useThrottle } from "@/utils/hooks";

interface CustomTabsProps {
  tabs: {
    text: string;
    realText: string;
    activeClass: string;
    defaultClass: string;
  }[];

  initAllData: () => void

  keyword: string
  searchStart: boolean
  searchCallback: () => void
}

const voteBtnImage = CONCAT_CDN_IMAGE_ORIGIN('/vote/点击投票.png')

const loveBtnImage = CONCAT_CDN_IMAGE_ORIGIN('/vote/love.png')

const NoVotePic = CONCAT_CDN_IMAGE_ORIGIN("/user/not-vote.png");

export const CustomTabsProjectVote = (props: CustomTabsProps) => {

  const limit = 10

  const { keyword, searchStart, searchCallback, initAllData } = props

  const [current, setCurrent] = useState(0);

  const [page, setPage] = useState(1)

  const [programType, setProgramType] = useState(-1)

  const [data, setData] = useState<IItem[]>([])

  // const [refreshTrigger, setRefreshTrigger] = useState(false)
  const [top, setTop] = useState(-1)


  const handleClick = (value: number) => {
    setCurrent(value);
    setTop(0)
    setPage(1)
    setProgramType(programTypeConfig[value])
  };

  useEffect(() => {
    CustomRequest.get(apiVotes, {
      limit,
      current: page,
      programType,
      keyword
    }).then((res: { data: { items: IItem[] } }) => {
      if (res && page === 1) {
        setData(res.data.items)
      }
      if (res && page > 1) {
        setData(data.concat(res.data.items))
        if (res.data.items.length === 0) {
          Taro.showToast({
            title: '没有数据了',
            icon: 'none',
            duration: 2000
          })
        }
      }
    })
  }, [page, programType]);

  useEffect(() => {
    if (keyword.length > 0 && searchStart) {
      CustomRequest.get(apiVotes, {
        limit: 200,
        current: 1,
        programType: -1,
        keyword
      }).then((res: { data: { items: IItem[] } }) => {
        if (res) {
          setData(res.data.items)
          searchCallback()
        }
      })
    }
    // 初始化
    if (keyword === '') {
      CustomRequest.get(apiVotes, {
        limit,
        current: 1,
        programType: -1,
        keyword
      }).then((res: { data: { items: IItem[] } }) => {
        if (res) {
          setData(res.data.items)
        }
      })
    }

  }, [keyword, searchStart]);


  // useEffect(() => {
  //   CustomRequest.get(apiVotes, {
  //     limit: 10,
  //     current: 1,
  //     programType: programType,
  //     keyword
  //   }).then((res: { data: { items: IItem[] } }) => {
  //     if (res) {
  //       setData(res.data.items)
  //     }
  //   })
  // }, [programType]);

  const onVote = useThrottle((programId: string | number, index: number) => {
    CustomRequest.post(apiVotePost, {
      inviteCode: Taro.getStorageSync('scene'),
      programId
    }).then((res: any) => {
      if (res.code === "200000") {
        Taro.showToast({
          title: '投票成功',
          icon: 'success',
          duration: 2000
        })

        const votedData = data.concat()

        votedData[index].totalVotes++

        setData(votedData)

        initAllData()

      }
    })
  }, 3000)

  const onScrollToBottom = (_e) => {
    setPage(page + 1)
  }

  return (
    <View className="custom-tabs">
      <View>
        <View className="wrap">
          {props.tabs &&
            props.tabs.map((item, index) => {
              return (
                <View
                  key={index}
                  className={
                    current === index ? item.activeClass : item.defaultClass
                  }
                  onClick={() => handleClick(index)}
                >
                  { current === index ? item.realText : item.text}
                </View>
              );
            })}
        </View>
      </View>
      {/* <AtTabs current={current} onClick={handleClick} tabList={[]}>
        <AtTabsPane current={current} index={0}> */}
      <View className="content">
        {
          data.length > 0 ? <View className="tips">注：项目展示顺序按照申报时间排列</View>
            : ''
        }
        <ScrollView
          style={{
            height: '70vh',
            marginTop: '20rpx',
            marginBottom: '100rpx'
          }}
          onScroll={() => {
            if (top === 0) {
              setTop(-1)
            }
          }}
          scrollY={true}
          scrollTop={top}
          onScrollToLower={onScrollToBottom}
        >
          {/**展示节目box */}
          {
            data.map((item, index) => (
              <View className="box">
                <View className="item">
                  <View className="img">
                    <Image
                      src={item.programImage.split(',')[0]}
                      mode="widthFix"
                      onClick={() => {
                        Taro.previewImage({
                          current: item.programImage.split(',')[0],
                          urls: item.programImage.split(',')
                        })
                      }}
                      style={{ width: "100%", borderRadius: '10rpx' }}
                    />
                  </View>
                  <View className="detail">
                    <ShowMessageBox item={item} />
                  </View>
                </View>
                <View className="btn">
                  <Image src={voteBtnImage} style={{ width: '100%' }} mode='widthFix'
                    onClick={() => {
                      onVote(item.id, index)
                    }}
                  />
                  <View className='result'>
                    <Image src={loveBtnImage} style={{ width: '50%' }} mode='widthFix' />
                    <View>票数：{item.totalVotes}</View>
                  </View>
                </View>
              </View>
            ))
          }

          {
            data.length === 0 ? <View className="no-data">
              <Image src={NoVotePic} mode="widthFix" style={{ width: "80%" }} />
              <View>暂无数据</View>
            </View> : ""
          }
        </ScrollView>

      </View>
      {/* </AtTabsPane>
        <AtTabsPane current={current} index={1}>
          <View className="content">2</View>
        </AtTabsPane>
        <AtTabsPane current={current} index={2}>
          <View className="content">3</View>
        </AtTabsPane>
        <AtTabsPane current={current} index={3}>
          <View className="content">4</View>
        </AtTabsPane>
        <AtTabsPane current={current} index={4}>
          <View className="content">5</View>
        </AtTabsPane>
      </AtTabs> */}
      {/**本活动最终解释权归组委会所有 */}
      <View className='explain'>
        本活动最终解释权归组委会所有
      </View>
    </View>
  );
};
